﻿using System;
using System.Linq;
using System.Web.Mvc;
using easyccms.BusinessLayer;
using easyccms.BusinessLayer.Entities;
using easyccms.BusinessLayer.Repositories;
using easyccms.WebUI.Areas.Administrator.Models;
using easyccms.WebUI.Code;
using easyccms.WebUI.Infrastructure;

namespace easyccms.WebUI.Areas.Administrator.Controllers
{
    /// <summary>
    /// Controller for menu item.
    /// </summary>
    public class MenuItemController : Controller, IAdminController
    {
        /// <summary>
        /// Instance of Menu item repository.
        /// </summary>
        private IMenuItemRepository _menuItemRepository{
            get { return DependencyInjector.Resolve<IMenuItemRepository>(); }
        }


        /// <summary>
        /// Instance of unit of work.
        /// </summary>
        private IUnitOfWork _unitOfWork{
            get {return _menuItemRepository.GetUnitOfWork(); }
        }


        /// <summary>
        /// Instace of menu repository.
        /// </summary>
        private IMenuRepository _menuRepository{
            get { return DependencyInjector.Resolve<IMenuRepository>(); }
        }


        /// <summary>
        /// Instance of user provider
        /// </summary>
        private UserProvider _userProvider = new UserProvider();

    
        //
        // GET: /Administrator/MenuItem/

        /// <summary>
        /// Indexes this instance.
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View(this._menuItemRepository.All.Where(x=>!x.Deleted));
        }


        //
        // GET: /Administrator/MenuItem/Create

        /// <summary>
        /// Creates this instance.
        /// </summary>
        /// <returns></returns>
        public ActionResult Create()
        {
            MenuItemModel menuItemModel = new MenuItemModel
                                              {
                                                  MenuItem = new MenuItem(),
                                                  Menus =
                                                      this._menuRepository.All.AsEnumerable().Select(
                                                          x =>
                                                          new SelectListItem()
                                                              {Text = x.Name, Value = x.MenuId.ToString()})
                                                      .ToList()
                                              };

            return View(menuItemModel);
        } 

        //
        // POST: /Administrator/MenuItem/Create

        /// <summary>
        /// Creates the specified menu item.
        /// </summary>
        /// <param name="menuItem">The menu item.</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Create([Bind(Exclude = "Menu")]MenuItem menuItem)
        {
            menuItem.Created = DateTime.Now;
            menuItem.User = this._userProvider.GetCurrentUser();
            int menuId = Convert.ToInt16(Request["menuItem.Menu.MenuId"]);
            menuItem.Menu = _menuRepository.Load(menuId);
            menuItem.DisplayUntil = DateTime.Now.AddYears(1);

            if (ModelState.IsValid)
            {
                try
                {
                    this._unitOfWork.StartTransaction();
                    _menuItemRepository.Save(menuItem);
                    this._unitOfWork.CommitTransaction();
                    
                    return RedirectToAction("Index");
                }
                catch
                {
                    this._unitOfWork.RollbackTransaction();
                }
            }

            MenuItemModel menuItemModel = new MenuItemModel();
            menuItemModel.MenuItem = menuItem;
            menuItemModel.Menus =
                this._menuRepository.All.AsEnumerable().Where(x=>!x.Deleted).Select(x => new SelectListItem() { Text = x.Name, Value = x.MenuId.ToString() }).ToList();

            return View(menuItemModel);
        }
        
        //
        // GET: /Administrator/MenuItem/Edit/5

        /// <summary>
        /// Edits the specified id.
        /// </summary>
        /// <param name="id">The id.</param>
        /// <returns></returns>
        public ActionResult Edit(int id)
        {
            MenuItemModel menuItemModel = new MenuItemModel
            {
                MenuItem = this._menuItemRepository.Load(id),
                Menus =
                    this._menuRepository.All.AsEnumerable().Select(
                        x =>
                        new SelectListItem() { Text = x.Name, Value = x.MenuId.ToString() })
                    .ToList()
            };

            return View(menuItemModel);
        }

        //
        // POST: /Administrator/MenuItem/Edit/5

        /// <summary>
        /// Edits the specified menu item.
        /// </summary>
        /// <param name="menuItem">The menu item.</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Edit([Bind(Exclude = "Menu")]MenuItem menuItem)
        {
            menuItem.Created = DateTime.Now;
            menuItem.User = this._userProvider.GetCurrentUser();
            int menuId = Convert.ToInt16(Request["menuItem.Menu.MenuId"]);
            menuItem.Menu = _menuRepository.Load(menuId);
            menuItem.DisplayUntil = DateTime.Now.AddYears(1);

            if (ModelState.IsValid)
            {
                try
                {
                    this._unitOfWork.StartTransaction();
                    _menuItemRepository.Save(menuItem);
                    this._unitOfWork.CommitTransaction();


                    return RedirectToAction("Index");
                }
                catch
                {
                    this._unitOfWork.RollbackTransaction();
                }
            }

            MenuItemModel menuItemModel = new MenuItemModel
                                              {
                                                  MenuItem = menuItem,
                                                  Menus =
                                                      this._menuRepository.All.AsEnumerable().Where(x => !x.Deleted).
                                                      Select
                                                      (x =>
                                                       new SelectListItem() {Text = x.Name, Value = x.MenuId.ToString()})
                                                      .
                                                      ToList()
                                              };

            return View(menuItemModel);
        }

        /// <summary>
        /// Moves to bin.
        /// </summary>
        /// <param name="id">The id.</param>
        /// <returns></returns>
        public ActionResult MoveToBin(int id)
        {
            MenuItem itemToUpdate = this._menuItemRepository.Load(id);
            itemToUpdate.Deleted = true;
            this._unitOfWork.StartTransaction();
            this._menuItemRepository.Save(itemToUpdate);
            this._unitOfWork.CommitTransaction();
            return RedirectToAction("Index");
        }

        /// <summary>
        /// Bins this instance.
        /// </summary>
        /// <returns></returns>
        public ActionResult Bin()
        {
            return View(this._menuItemRepository.All.Where(x => x.Deleted));
        }

        /// <summary>
        /// Bins the delete.
        /// </summary>
        /// <param name="id">The id.</param>
        /// <returns></returns>
        public ActionResult BinDelete(int id)
        {
            TempData["SelectedTab"] = "MenuItem";

            MenuItem itemToUpdate = this._menuItemRepository.Load(id);
            itemToUpdate.Deleted = true;
            this._unitOfWork.StartTransaction();
            this._menuItemRepository.Delete(itemToUpdate);
            this._unitOfWork.CommitTransaction();

            return RedirectToAction("Bin","Management");

        }

        /// <summary>
        /// Bins the restore.
        /// </summary>
        /// <param name="id">The id.</param>
        /// <returns></returns>
        public ActionResult BinRestore(int id)
        {
            TempData["SelectedTab"] = "MenuItem";

            MenuItem itemToUpdate = this._menuItemRepository.Load(id);
            itemToUpdate.Deleted = false;
            this._unitOfWork.StartTransaction();
            this._menuItemRepository.Save(itemToUpdate);
            this._unitOfWork.CommitTransaction();

            return RedirectToAction("Bin", "Management");

        }
    }
}
